package com.tuanzi.loan.web.bean.family.sms;

import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.sms.SmsPhoneSource;
import com.tuanzi.loan.business.entity.sms.SmsCalculateTask;
import com.tuanzi.loan.business.entity.sms.SmsCalculateTaskStatus;
import com.tuanzi.loan.business.service.sms.SmsCalculateTaskService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.exception.ValidateException;
import com.tuanzi.loan.vo.request.family.SmsCalculateTaskSearchRequest;
import com.tuanzi.loan.vo.response.family.SmsCalculateTaskSearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.family.SmsCalculateTaskLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import static com.tuanzi.loan.business.constants.DictionaryCode.SMS_CALCULATE_STATUS;
import static com.tuanzi.loan.business.constants.DictionaryCode.SMS_PLATFORM_CHANNEL;

/**
 * @author Ray 2017/09/21
 */
@Data
@Slf4j
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class SmsCalculateTaskBean extends JSFListingBean<SmsCalculateTaskSearchRequest, SmsCalculateTaskSearchResponse> {

	private static final long serialVersionUID = -2152778554108785342L;

	@Autowired
	private SmsCalculateTaskService smsCalculateTaskService;
	private String taskErrorReason;

	@PostConstruct
	private void init() {
		initLazyDataModel();
	}

	public void onReset() {
		initLazyDataModel();
	}

	private void initLazyDataModel() {
		$ = new SmsCalculateTaskSearchRequest();
		lazyDataModel = new SmsCalculateTaskLazyDataModel($);
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(SMS_CALCULATE_STATUS, SMS_PLATFORM_CHANNEL);
	}

	/**
	 * 发送文本短信
	 * @param id
	 * @return
	 */
	public String onSend(Long id) {
		return redirect("/views/family/user-info/send-sms/send-sms.xhtml?id=" + id);
	}

	public String onBatchSend() {
		if (getSelectedRecords().parallelStream().filter(x -> x.getStatus().equals(SmsCalculateTaskStatus.CALCULATE_FAIL.ordinal())).count() > 0) {
			addErrorMessage("批量发送中含有计算失败任务, 请重新选择");
			return "";
		}
		String selectedIds = getSelectedRecords().parallelStream().map(SmsCalculateTaskSearchResponse::getId).map(x -> x.toString()).collect(Collectors.joining(","));
		return redirect("/views/family/user-info/send-sms/send-sms.xhtml?id=" + selectedIds);
	}

	/**
	 * 发送语音短信
	 * @param id
	 * @return
	 */
	public String onSendVoiceSms(Long id){
		return redirect("/views/family/user-info/send-sms/send-voice-sms.xhtml?id=" + id);
	}

	public String onViewCondition(Long id) {
		 SmsCalculateTask smsCalculateTask =  smsCalculateTaskService.findOne(id);
		 if(smsCalculateTask.getPhoneSource().equals(SmsPhoneSource.INNER)){
			 return redirect("/views/family/user-info/send-sms/sms-condition-view.xhtml?calculateTaskId=" + id);
		 }else if(smsCalculateTask.getPhoneSource().equals(SmsPhoneSource.OUTER)){
			 return redirect("/views/family/user-info/send-sms/external-sms-condition-view.xhtml?calculateTaskId=" + id);
		 }else if(smsCalculateTask.getPhoneSource().equals(SmsPhoneSource.IMPORT)){
		 	addWarnMessage("导入任务不可查看计算任务明细");
		 }
		 throw new ValidateException("计算任务类型错误");
	}

	public void onViewError(Long id) {
		SmsCalculateTask smsCalculateTask = smsCalculateTaskService.findOne(id);
		taskErrorReason = smsCalculateTask.getErrorReason();
	}

	public void onActive(Long smsCalculateTaskId){
		smsCalculateTaskService.activeTask(smsCalculateTaskId);
		addSuccessfullyMessage();
	}


	public void onCancel(Long smsCalculateTaskId) {
		smsCalculateTaskService.cancelTask(smsCalculateTaskId);
		addSuccessfullyMessage();
	}

	public void onRecalculate(Long smsCalculateTaskId) {
		smsCalculateTaskService.recalculate(smsCalculateTaskId);
		addSuccessfullyMessage();
	}


	// 任务名称
	private String name;
	// 手机号列表
	private List<String> phoneList;
	public void handleExternalPhone(FileUploadEvent event) {
		try {
			phoneList = IOUtils.readLines(event.getFile().getInputstream(),
					Charsets.UTF_8);

			//手机号去重
			phoneList = phoneList.stream().distinct().collect(Collectors.toList());
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 导入外部号码
	 */
	public void onImportPhones(){
		if(StringUtils.isBlank(name)){
			addErrorMessage("请输入任务名称");
			return;
		}

		if(CollectionUtils.isEmpty(phoneList)){
			addErrorMessage("没有数据导入！");
			return;
		}

		SmsCalculateTask smsCalculateTask =  smsCalculateTaskService.importPhones(name, phoneList);
		if(smsCalculateTask.getStatus().equals(SmsCalculateTaskStatus.CALCULATE_DONE)){
			addSuccessfullyMessage();
		}else{
			addErrorMessage("导入失败，请重新导入");
		}

		//重新初始化
		phoneList=null;
	}
}
